package com.company.search;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author shenhan
 * @create 2020/2/2 18:59
 * @description 二分查找前提：有序
 */
public class BinarySearch {
    public static void main(String[] args) {
        int[] arr = {-1, 8, 8, 8,8,8, 10, 89, 110, 1234};
        System.out.println(binarySearch(arr, 0, arr.length - 1, 8));
        System.out.println(binarySearchArr(arr, 0, arr.length - 1, 0));
    }

    public static int binarySearch(int[] arr, int left, int right, int value) {
        if (left > right) {
            return -1;
        }
        int mid = (left + right) / 2;
        int midVal = arr[mid];
        if (value > midVal) {
            return binarySearch(arr, mid + 1, right, value);
        } else if (value < midVal) {
            return binarySearch(arr, left, mid - 1, value);
        } else {
            return mid;
        }
    }

    private static List<Integer> binarySearchArr(int[] arr, int left, int right, int value) {
        if (left > right) {
            return Collections.emptyList();
        }
        int mid = (left + right) / 2;
        int midVal = arr[mid];
        if (value > midVal) {
            return binarySearchArr(arr, mid + 1, right, value);
        } else if (value < midVal) {
            return binarySearchArr(arr, left, mid - 1, value);
        } else {
            List<Integer> list = new ArrayList<>();
            int temp = mid - 1;
            while (temp >= 0 && arr[temp] == value) {
                list.add(temp);
                temp -= 1;
            }
            list.add(mid);
            temp = mid + 1;
            while (temp <= arr.length - 1 && arr[temp] == value) {
                list.add(temp);
                temp += 1;
            }
            return list;
        }
    }
}
